import { useEffect, useState } from 'react'

import { orgGetDetailApi, orgUpdatePasswordApi } from '@/api/app'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import APanel from '@/components/APanel'
import { REGEXP_PASSWORD } from '@/utils/constants'
import { HOSPITAL_ORG_TYPE_CONFIG } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditDrawer = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { organizationId } = row

  const [organizationDetail, setOrganizationDetail] = useState(null)

  useEffect(() => {
    if (!organizationId) return
    requestWithTry(orgGetDetailApi, { organizationId }).then(res => {
      setOrganizationDetail(res.data)
      form.setFieldsValue({
        ...res.data,
      })
    })
  }, [organizationId])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    <APanel key='basic' className='ml-10px' title='基本信息' />,
    {
      field: 'organizationName',
      label: '机构名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'type',
      label: '类型',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: HOSPITAL_ORG_TYPE_CONFIG.options,
        },
      },
    },
    {
      field: 'address',
      label: '地址',
      component: { name: 'AekTextArea' },
    },
    {
      field: 'userName',
      label: '管理员账号',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
        props: {
          disabled: !!organizationDetail,
        },
      },
    },
    {
      exclude: !!organizationDetail,
      field: 'password',
      label: '管理员密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    {
      exclude: !!organizationDetail,
      field: 'confirmedPassword',
      label: '确认密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    <APanel key='permission' className='ml-10px' title='系统权限' />,
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      organizationId,
      ...values,
    }
    await requestWithTry(orgUpdatePasswordApi, params)
  }
  return (
    <AekDrawer title={organizationId ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekDrawer>
  )
}

EditDrawer.PromiseThen = PromiseThen

export default EditDrawer
